package com.imooc.controller;

import com.imooc.common.config.ProjectUrlConfig;
import com.imooc.common.enums.ResultEnum;
import com.imooc.common.exception.SelllException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.net.URLEncoder;

@Slf4j
@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Resource
    WxMpService wxMpService;

    @Resource
    WxMpService wxOpenService;

    @Autowired
    ProjectUrlConfig projectUrlConfig;

    @RequestMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        String url = projectUrlConfig.getWechatMpAuthorize() + "http://sylimooc.nat300.top/sell/wechat/userInfo";
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_BASE, URLEncoder.encode(returnUrl));
        log.info("redirectUrl = {}", redirectUrl);
        return "redirect:" + redirectUrl;
    }

    @RequestMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = null;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("获取access_token异常：{}", e);
            throw new SelllException(ResultEnum.WEXIN_ERROR, e.getError().getErrorMsg());
        }

        if (wxMpOAuth2AccessToken == null) {
            throw new SelllException(ResultEnum.WEXIN_ERROR);
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("openId = {}", openId);
        return "redirect:" + returnUrl + "?openid=" + openId;
    }

    @RequestMapping("/qrAuthorize")
    public String qrAuthorize(@RequestParam("returnUrl") String returnUrl) {
        String url = projectUrlConfig.getWechatOpenAuthorize() + "/sell/wechat/qrUserInfo";
        String redirectUrl = wxOpenService.buildQrConnectUrl(url, WxConsts.QRCONNECT_SCOPE_SNSAPI_LOGIN, URLEncoder.encode(returnUrl));
        log.info("redirectUrl = {}", redirectUrl);
        return "redirect:" + redirectUrl;
    }

    @RequestMapping("/qrUserInfo")
    public String qrUserInfo(@RequestParam("code") String code,
                             @RequestParam("state") String returnUrl) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = null;
        try {
            wxMpOAuth2AccessToken = wxOpenService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("qrUserInfo 获取access_token异常：{}", e);
            throw new SelllException(ResultEnum.WEXIN_ERROR, e.getError().getErrorMsg());
        }

        if (wxMpOAuth2AccessToken == null) {
            throw new SelllException(ResultEnum.WEXIN_ERROR);
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("qrUserInfo openId = {}", openId);
        return "redirect:" + returnUrl + "?openid=" + openId;
    }
}
